package com.atguigu.tingshu.user.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.WxMaUserService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.tingshu.common.constant.PublicConstant;
import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.model.user.UserInfo;
import com.atguigu.tingshu.user.mapper.UserInfoMapper;
import com.atguigu.tingshu.user.service.UserInfoService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.jwt.Jwt;
import org.springframework.security.jwt.JwtHelper;
import org.springframework.security.jwt.crypto.sign.RsaSigner;
import org.springframework.security.jwt.crypto.sign.RsaVerifier;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    WxMaService wxMaService;
    @Autowired
    private RsaSigner rsaSigner;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Override
    public Map<String, Object> wxLogin(String code) {
        HashMap<String, Object> map = new HashMap<>();
        String openid = "";
        if (StringUtils.isEmpty(code)) {
            throw new GuiguException(201, "no");

        }
        //存在，调用微信服务端
        WxMaUserService userService = wxMaService.getUserService();
        WxMaJscode2SessionResult sessionInfo = null;
        try {
            sessionInfo = userService.getSessionInfo(code);
            openid = sessionInfo.getOpenid();
        } catch (WxErrorException e) {
            log.error("失败：{}", e.getMessage());
            throw new GuiguException(201, "失败");
        }

        //
        String refreshTokenKey = RedisConstant.USER_LOGIN_REFRESH_KEY_PREFIX + openid;
        String tokenFromRedis = redisTemplate.opsForValue().get(refreshTokenKey);
        if (!StringUtils.isEmpty(tokenFromRedis)) {
            Map<String, Object> map1 = new HashMap<>();
            map1.put("token", tokenFromRedis);
            return map1;
        }

        //根据openid判断库中是否存在用户
        LambdaQueryWrapper<UserInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserInfo::getWxOpenId, openid);
        UserInfo userInfo = userInfoMapper.selectOne(queryWrapper);
        if (userInfo == null) {
            //像user_infoz中插入用户信息
            userInfo = new UserInfo();
            userInfo.setWxOpenId(openid);
            userInfo.setNickname(System.currentTimeMillis() + "{ wk }" + UUID.randomUUID().toString().substring(0, 4).replace("-", ""));
            userInfo.setAvatarUrl("https://oss.aliyuncs.com/aliyun_id_photo_bucket/default_handsome.jpg");
            userInfo.setIsVip(0);
            userInfo.setVipExpireTime(new Date());
            int insert = userInfoMapper.insert(userInfo);
            log.info("注册用户：{}", insert > 0 ? "success" : "fail");
            //2.向tingshu_account中的user_account中插入用户账户
        }



        //生成token返回 传统方式生成token
        //String token = UUID.randomUUID().toString().substring(0, 4).replace("-", "");

        //RSA，非对称加密更安全（公钥：加密，验签，私钥）
        //定义一个载荷

        //使用security框架
        //后端存一份保存
        String accessToken = getKsonWebToken(openid, userInfo.getId());
        map.put("token", accessToken);//token前端写死
        //map.put("refreshToken", accessToken);//假装有一个（并没有做）
        String accessTokenKey = RedisConstant.USER_LOGIN_KEY_PREFIX + openid;
        //给用户登录信息设置过期时间
        //双token机制，accesstoken(分钟，小时),reflashtoken（天，月）

        //refreshtoken

        //redisTemplate.opsForValue().set(accessTokenKey,accessToken,10, TimeUnit.MINUTES);//线上短一点
        //自己测试长一点
        redisTemplate.opsForValue().set(accessTokenKey,accessToken,20, TimeUnit.DAYS);
        redisTemplate.opsForValue().set(refreshTokenKey,accessToken,180, TimeUnit.DAYS);
        return map;
    }



    private String getKsonWebToken(String openid, Long userId) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("id", userId);
        jsonObject.put("openid", openid);
        Jwt jwt = JwtHelper.encode(jsonObject.toString(), rsaSigner);//公钥私钥，对象
        String encoded = jwt.getEncoded();
        return encoded;
    }








    @Override
    public Map<String, Object> getNewRefreshToken() {
        HashMap<String, Object> result = new HashMap<>();
        //搞清楚流程，从哪里获取token,然后解析token，获取openid(前端的请求头里)
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        String token = request.getHeader("token");
        if (StringUtils.isEmpty(token)) {
            throw new GuiguException(201, "未登录");
        }

        //校验token
        Jwt jwt = JwtHelper.decodeAndVerify(token, new RsaVerifier(PublicConstant.PUBLIC_KEY));
        //获取载荷
        String claims = jwt.getClaims();
        //由于前端存储数据是map形式，解析为map
        Map map = JSONObject.parseObject(claims, Map.class);
        Object openid = map.get("openid");
        Object userId = map.get("id");

        String accessTokenKey = RedisConstant.USER_LOGIN_KEY_PREFIX + openid;
        String refreshTokenKey = RedisConstant.USER_LOGIN_REFRESH_KEY_PREFIX + openid;
        //获取redfreshtoken
        String resfreshToken = redisTemplate.opsForValue().get(refreshTokenKey);
        //判断是否过期
        if (!StringUtils.isEmpty(resfreshToken)) {

            //不过期，生成新的令牌
            String jsonWebToken = getKsonWebToken(String.valueOf(openid), Long.parseLong(userId.toString()));
            //redisTemplate.opsForValue().set(accessTokenKey,accessToken,10, TimeUnit.MINUTES);//线上短一点
            //自己测试长一点
            redisTemplate.opsForValue().set(accessTokenKey,jsonWebToken,20, TimeUnit.DAYS);
            redisTemplate.opsForValue().set(refreshTokenKey,jsonWebToken,180, TimeUnit.DAYS);
            result.put("token", jsonWebToken);
            return result;
        }
        else {
            result.put("1", "v");
            //过期重新登陆
        }
        return result;
    }
}

